package com.bulletelc.apollopre.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Build;

import com.bulletelc.apollopre.R;
import com.bulletelc.apollopre.utils.ToastUtil;

/**
 * Created by CX on 2018/3/13.
 * 网络状态监听接受者
 */

public class NetworkStateReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //检查api是否大于23，因为23之后getNetworkInfo(int networkType)被弃用
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            //获得connectivityManager对象
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            //获取ConnectivityManager对象对应的NetworkInfo对象
            //获取wifi网络信息
            NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            //获取移动网络信息
            NetworkInfo mobileNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (!wifiNetworkInfo.isConnected() && !mobileNetworkInfo.isConnected()) {
                ToastUtil.showLongToast(context, R.string.network_msg);
            }
        } else {
            //api大于23时用次方法
            //获得ConnectivityManager的对象
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            //获取所有网络信息
            Network[] netWorks = connectivityManager.getAllNetworks();
            //循环取出网络连接信息
            for (int i = 0; i < netWorks.length; i++) {
                //获得ConnectivityManager对应对象的NetworkInfo对象
                NetworkInfo networkInfo = connectivityManager.getNetworkInfo(netWorks[i]);
                if (!networkInfo.isConnected()) {
                    ToastUtil.showLongToast(context, R.string.network_msg);
                }
            }
        }
    }
}
